<script setup>
import { ref, onMounted } from 'vue'

// 定义响应式数据
const titles = ref([])
const loading = ref(true)
const error = ref('')

// 获取文章标题
const getTitles = async () => {
  try {
    // 首先尝试从storage中获取标题
    const result = await new Promise(resolve => {
      chrome.storage.local.get(['juejinTitles'], resolve)
    })
    
    if (result && result.juejinTitles && result.juejinTitles.length > 0) {
      // 如果storage中有数据，直接使用
      titles.value = result.juejinTitles
      error.value = ''
      loading.value = false
      return
    }
    
    // 如果storage中没有数据，再查询当前活动标签页
    const [activeTab] = await new Promise(resolve => {
      chrome.tabs.query({active: true, currentWindow: true}, resolve)
    })
    
    // 检查当前页面是否为掘金网站
    if (activeTab.url && activeTab.url.includes('juejin.cn')) {
      // 向content script发送消息请求文章标题
      const response = await new Promise(resolve => {
        chrome.tabs.sendMessage(activeTab.id, {action: 'getTitles'}, resolve)
      })
      
      // 处理响应
      if (response && response.titles && response.titles.length > 0) {
        titles.value = response.titles
        error.value = ''
      } else {
        // 没有找到标题
        error.value = '未找到文章标题，请稍后重试'
      }
    } else {
      // 当前页面不是掘金网站
      error.value = '请在掘金网站上使用此扩展程序'
    }
  } catch (err) {
    // 处理错误
    error.value = '获取标题时出错，请确保扩展程序已在掘金页面上正确加载'
    console.error('Error:', err)
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取标题
onMounted(() => {
  getTitles()
})
</script>

<template>
  <div class="container">
    <h2>掘金文章标题</h2>
    <div v-if="loading" class="loading">正在获取文章标题...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <ul v-else>
      <li v-for="(title, index) in titles" :key="index">{{ title }}</li>
    </ul>
  </div>
</template>

<style scoped>
.container {
  width: 400px;
  min-height: 300px;
  padding: 10px;
  font-family: Arial, sans-serif;
}

h2 {
  color: #1e80ff;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

li:last-child {
  border-bottom: none;
}

.loading {
  color: #999;
  font-style: italic;
}

.error {
  color: #e53935;
}
</style>
